//
//  ZComposeView.swift
//  swift-weibo
//
//  Created by zero on 17/3/27.
//  Copyright © 2017年 zero. All rights reserved.
//

import UIKit
import pop

class ZComposeView: UIView {

    
    //  父控制器
    var target:UIViewController?
    
    //  记录按钮的缓存池
    var buttonArray:[UIButton] = [UIButton]()
   
    override init(frame: CGRect) {
        super.init(frame: UIScreen.main.bounds)
    
        //  布局
        setupUI()
    }
    
    
    //  布局
    private func setupUI(){
        
        backgroundColor = UIColor.white
        

//        addSubview(imgView!)
        
        addSubview(imgFlag)
        
        //  约束
        imgFlag.snp.makeConstraints { (make) in
            
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
        
        
        //  添加按钮
        getComposeButton()
        
    }
    
    //  类方法展示
    class func show(targer:UIViewController) {
        
        let composeView = ZComposeView()
        
        //  记录父控制器
        composeView.target = targer
        
        targer.view.addSubview(composeView)
        
        
        //  添加按钮的动画
        composeView.addSixButtonAnimation(isup: true)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //  懒加载
    private lazy var imgView:UIImageView? = {
       
        let imgV:UIImageView = UIImageView(frame: self.bounds)
        
        imgV.image = UIImage.getImageForScreen()
        
        return imgV
    }()
    
    private lazy var imgFlag:UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
}
//MARK:
extension ZComposeView{
    
    fileprivate func addSixButtonAnimation(isup:Bool){
        
        let buttonYMargin: CGFloat = isup == true ? -350 : 350
        
        buttonArray = isup == true ? buttonArray : buttonArray.reversed()
        // 遍历数组
        for (i,button) in buttonArray.enumerated(){
            // 实例化弹簧动画对象
            let anSpring = POPSpringAnimation(propertyNamed: kPOPViewCenter)!
            // 设置toValue
            anSpring.toValue = CGPoint(x: button.center.x, y: button.center.y + buttonYMargin)
            // 开始时间 CACurrentMediaTime() 系统绝对时间
            anSpring.beginTime = CACurrentMediaTime() + Double(i)*0.025
            // 振幅
            anSpring.springBounciness = 10.0
            // 设置动画
            button.pop_add(anSpring, forKey: nil)
        }

    }
    
}

//MARK: 创建按钮的方法
extension ZComposeView{
    
    
    //  得到按钮
    fileprivate func getComposeButton(){
        //  获取模型数组
        let composeModelArray = getPlistData()
        
        //  按钮的大小
        let buttonW:CGFloat = 80
        let buttonH:CGFloat = 110
        
        //  按钮间的间距
        let itemMargin:CGFloat = (UIScreen.main.bounds.size.width - buttonW * 3) / 4
        
        for (i,model) in composeModelArray.enumerated(){
            
            //  计算行列
            let row = CGFloat(i / 3)
            let col = CGFloat(i % 3)

            //  创建按钮
            let button = ZComposeButton()
            button.setImage(UIImage(named:model.icon!), for: .normal)
            button.setTitle(model.title, for: .normal)
            button.setTitleColor(UIColor.black, for: .normal)
            button.frame = CGRect(x: itemMargin + col * (buttonW + itemMargin), y: row * (buttonH + itemMargin) + UIScreen.main.bounds.size.height, width: buttonW, height: buttonH)
            
            button.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
            
            //  传递模型数据
            button.buttonModel = model
            //  添加到缓存池中
            buttonArray.append(button)
            
            addSubview(button)
            
        }
        
    }
    
    //  按钮的点击事件
    @objc fileprivate func buttonClick(button:ZComposeButton){
        
        UIView.animate(withDuration: 0.25, animations: {
            
            for btn in self.buttonArray{
                
                btn.alpha = 0.2
                
                if btn == button{

                    btn.transform = CGAffineTransform(scaleX: 2, y: 2)
                }else{

                    btn.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)

                }
                
            }
            
        }) { (_) in
            
            UIView.animate(withDuration: 0.25, animations: {
                
                for btn in self.buttonArray{
                    
                    btn.alpha = 1
                    btn.transform = CGAffineTransform.identity
                }
                
            }, completion: { (_) in
                
                //  完成动画后的跳转 
                //  判断不为nil
//                guard let className = button.buttonModel?.classname else{
//                    
//                    return
//                }
                
                // 根据字符串加载一个类
//                guard let classNameVC = NSClassFromString(className) as? UIViewController.Type else{
//
//                    return
//                }
//                let classNameVC = NSClassFromString(className) as! UIViewController.Type
                let VC = ZComposeViewController()
                
            
    
                self.target?.present(ZMainNavigationViewController(rootViewController:VC), animated: true, completion: {
                    
                    self.removeFromSuperview()
                })
            })
            
        }
        
    }
    
    //  从plist中读取数据
    fileprivate func getPlistData() -> [ZComposeModel]{
        
        let filePath = Bundle.main.path(forResource: "compose.plist", ofType: nil)
        
        let array = NSArray(contentsOfFile: filePath!)
        
        let tempArray = NSArray.yy_modelArray(with: ZComposeModel.self, json: array!) as! [ZComposeModel]
        
        return tempArray
    }
}



//MARK: 点击View的方法
extension ZComposeView{
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        
        addSixButtonAnimation(isup: false)
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.4) {
            
            self.removeFromSuperview()
            
        }
        
    }
}
